package com.liuzy.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuzy.tool.HTTP;
import com.liuzy.util.Util;

/**
 * JSONP代理服务
 * @author liuzy
 * @since 2015年10月18日
 */
public class JsonpServlet extends HttpServlet {

	private static final long serialVersionUID = 7028490050555554247L;

	private String url;
	private String method;
	private String type;
	private String callback;
	private Map<String, String> params;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String query = request.getQueryString();
		Util.log("req->", request.getServletPath() + "?" + query);
		try {
			if (!query.contains("?") || (!query.startsWith("url=http://") && !query.startsWith("url=https://"))) {
				response.getWriter().write("error");
				return;
			}
			String[] temp = query.split("\\?");
			url = temp[0].substring(4);
			params = Util.kv2map(temp[1]);
			method = params.get("method");
			params.remove("method");
			type = params.get("type");
			params.remove("type");
			callback = params.get("callback");
			params.remove("callback");
			params.remove("_");

			String result = "";
			HTTP http = new HTTP();
			if (type != null && type.toUpperCase().equals("JSON")) {
				http.put2header("Content-Type", "application/json");
				result = http.doPOST(url, null, null, params, true);
			} else {
				if (method != null && method.toUpperCase().equals("POST")) {
					result = http.doPOST(url, null, null, params);
				} else {
					result = http.doGET(url, params);
				}
			}

			if (callback != null && !callback.isEmpty())
				result = callback + "('" + result + "');";
			Util.log("res->", result);
			response.setContentType("text/javascript; charset=utf-8");
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
